#! /usr/bin/python

import atom
import gdata
import gdata.contacts
import gdata.contacts.service

def AuthUrl():
	gd_client = gdata.contacts.service.ContactsService()
	next = 'https://bookmarkshare.planework.com/authed?url=www.planework.com'
	scope = 'https://www.google.com/m8/feeds/ https://mail.google.com/mail/feed/atom/'
	#scope = 'https://www.google.com/m8/feeds/profiles/domain/planework.com/full'
	secure =  True
	session = True
	return gd_client.GenerateAuthSubURL(next, scope, secure, session).to_string()

def SetPrivateKey(filename):
	try:
		f = open(filename)
		rsa_private_key = f.read()
		f.close()
	except IOError, (errno, strerror):
		raise 'I/O error(%s): %s' % (errno, strerror)
	return rsa_private_key

def PrintContactList(entries):
	list = ''
	for i, entry in enumerate(entries):
        	list += '%s, %s' % (i + 1, str(entry.title.text))
                for email in entry.email:
                        if email.primary and email.primary == 'true':
                                list += ', %s\n' % str(email.address)
        return list

def Authed(req):
	gd_client = gdata.contacts.service.ContactsService()
	rsa_key = SetPrivateKey('/var/www/hsrtestbed/planework.pem')
	url = 'https://' + req.hostname + req.unparsed_uri
	decryptedtoken = gdata.auth.extract_auth_sub_token_from_url(url,rsa_key=rsa_key)
	gd_client.SetAuthSubToken(str(decryptedtoken))
	gd_client.UpgradeToSessionToken() #:token)
	max_results = 999	
	query = gdata.contacts.service.ContactsQuery()
	query.max_results = max_results
	feed = gd_client.GetContactsFeed(query.ToUri())
	#feed = gd_client.GetContactsFeed()
	return PrintContactList(feed.entry)
